package com.sise.netty.Gzip流应用;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author idea
 * @data 2019/4/19
 */
public class GzipUtil {

    /**
     * 压缩方式
     *
     * @param source 源数据
     * @return
     * @throws IOException
     */
    public static byte[] zip(byte[] source) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream zipOut = new GZIPOutputStream(out);
        zipOut.write(source);
        zipOut.finish();
        byte[] target = out.toByteArray();
        zipOut.close();
        return target;
    }


    /**
     * 解压方式
     *
     * @param source
     * @return
     * @throws IOException
     */
    public static byte[] unzip(byte[] source) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(source);
        //使用jdk提供的专门用于进行数据要说处理的字节数组数据
        GZIPInputStream zipIn = new GZIPInputStream(in);
        byte[] temp = new byte[256];
        int length = 0;
        while ((length = zipIn.read(temp, 0, temp.length)) != -1) {
            out.write(temp, 0, length);
        }
        //由字节数组输出的流数据转换为字节数据
        byte[] target = out.toByteArray();
        zipIn.close();
        out.close();

        return target;
    }

    /**
     * 图片压缩解压处理
     *
     * @throws IOException
     */
    public static void gzipPicDemo() throws IOException {
        FileInputStream fis = new FileInputStream(new File("C:\\Users\\Administrator\\Pictures\\logo.jpg"));
        byte[] temp = new byte[fis.available()];
        int length = fis.read(temp);
        System.out.println("文件原先的长度为：" + length);
        byte[] zipArray = GzipUtil.zip(temp);
        System.out.println("压缩之后的文件长度为：" + zipArray.length);
        byte[] unzipArr = GzipUtil.unzip(zipArray);
        System.out.println("解压之后的文件长度为：" + unzipArr.length);
        fis.close();
    }


    /**
     * 文字压缩解压处理
     *
     * @throws IOException
     */
    public static void gzipStrDemo() throws IOException {
        String temp = "iadnskldjasklsdjklzxcnj,wqjklllllllasdasdsaaaaaaaaaaaaaaaaaaasdqweqwe asdqwweqweqwe1233123dsa qwgeubjmcbukqhw aukhedkjhzxdmnbamnsbdjkqghwejkbqwjebjkqwh qwhudyhasukjdbnj lllllllasdasdasd";
        System.out.println("原先的长度为：" + temp.getBytes().length);
        byte[] zipArray = GzipUtil.zip(temp.getBytes());
        System.out.println("压缩之后的长度为：" + zipArray.length);
        byte[] unzipArr = GzipUtil.unzip(zipArray);
        System.out.println("解压之后的长度为：" + unzipArr.length);
    }

    public static void main(String[] args) throws IOException {
        gzipStrDemo();
    }
}
